<template>
  <div>
    <div class="top">
      <div style="float: right;margin-right: 10px;">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
      </div>
      <div style="float: right;margin-right: 10px;">
        <el-select v-model="is_sended" placeholder="状态" filterable clearable @change="handleSearch">
          <el-option label="所有" value="" />
          <el-option label="发送成功" value="true" />
          <el-option label="发送失败" value="false" />
        </el-select>
      </div>
      <div style="float: right;margin-right: 10px;">
        <el-select v-model="processor_id" placeholder="处理人" class="head" filterable clearable @change="handleSearch">
          <el-option label="所有" value="" />
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.username"
            :value="user.id"
          />
        </el-select>
      </div>
      <div style="clear: both" />
    </div>
    <el-table
      v-loading="listLoading"
      :data="data"
      fit
      highlight-current-row
      style="margin-top:10px; width: 100%"
      @sort-change="handleSort"
    >
      <el-table-column align="left" width="300" prop="mail_to" label="收件人" />
      <el-table-column align="left" label="简要" prop="subject" sortable="custom">
        <template slot-scope="scope">
          <span style="display:block;" :class="{'unread': !scope.row.readed, 'readed': scope.row.readed}">{{ scope.row.subject }}</span>
          <span style="display:block; overflow: hidden;white-space: nowrap;text-overflow: ellipsis;max-width: 900px">{{ scope.row.short_content }}</span>
          <span>id:{{ scope.row.message_id }}</span>
          <span>references:{{ scope.row.references }}</span>
          <span>in_reply_to:{{ scope.row.in_reply_to }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="发送状态" prop="subject" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.is_sended ? '成功' : '未发送' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100" prop="mail_date" label="时间" />
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">

          <el-button size="mini" type="success" @click="handleDrawer(scope.row)">回复</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <crmsendmail :mailbox_data="currentrow" :is-visible="drawer" @close="drawer=false;" />
    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">

        <el-form-item v-if="action !== 'delete'" label="稍后">
          <el-checkbox v-model="temp.later">是否稍后处理</el-checkbox>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="处理人">
          <el-select v-model="temp.processor_id" placeholder="处理人" class="head" filterable clearable>
            <el-option label="不指定" value="" />
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, GetBody } from '@/api/crm/crmmailbox'
import qs from 'qs'
import Tinymce from '@/components/Tinymce'
import Crmsendmail from './elements/crmsendmail'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmmaildraft',
  components: { Crmsendmail, Tinymce },
  data() {
    return {
      iframeSrc: '',
      sendMailVisible: false,
      mail_to: '',
      mail_receiver: '',
      emailbox_id: '',
      pre_subject: '',
      pre_body: '',
      replayConfigDialogVisible: false,
      notCustomerDialogVisible: false,
      replatemplateloading: false,
      orderinfoVisible: false,
      orderinfokeyword: '',
      drawer: false,
      data: [],
      listLoading: false,
      kwInput: '',
      is_sended: '',
      later: false,
      processor_id: '',
      order_by: 'create_at',
      order_desc: 1,
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,
      mailbody_src: '',
      currentrow: {
        subject: '',
        body: '',
        mail_from: '',
        mail_to: '',
        mail_receiver: ''
      },
      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        later: true,
        processor_id: '',
        id: ''
      },
      width: '',
      projects: [],
      innerDialogVisible: false,
      replayDialogVisible: false,
      replaytitle: '回复邮件',
      chooseReplayTemplate: '',
      replayTemplateAll: true,
      replaytemplateoptions: [],
      replaytemplatebody: '',
      replyemail: {
        mailbox_id: '',
        body: '',
        subject: '',
        send_account: '',
        receiver_email: ''
      },
      order_datas: [],
      order_total: 0,
      orderloading: false,
      paypalcase_data: [],
      email_accounts: [],
      users: []
    }
  },
  computed: {
    // 目录名称
    k: function() {
      return this.$route.query.k
    }
  },
  watch: {
    webVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    }
  },
  created() {
    if (this.k) {
      this.kwInput = this.k
    }
    // this.getReplyTemplate({ 'kw': '', 'pagesize': 20 })
    this.handleSearch()
  },
  methods: {
    fetchEmailBody() {
      GetBody(qs.stringify({
        mail_token: this.currentrow.mail_token
      }))
        .then(response => {
          // 确保response是字符串形式的HTML内容
          const htmlContent = response // 或者如果response是一个对象，你可能需要 response.data 或类似的属性

          // 添加缺失的DOCTYPE声明、<html>、<body>标签
          const fullHtmlContent = `<!DOCTYPE html><html><body>${htmlContent}</body></html>`

          // 创建一个Blob对象，类型为"text/html"
          const blob = new Blob([fullHtmlContent], { type: 'text/html' })
          // 创建一个指向该Blob的URL
          this.iframeSrc = URL.createObjectURL(blob)
        }).catch(err => {
          console.log(err)
        })
    },
    handleSendMail() {
      // Get(this.replyemail).then(response => {
      //   this.maindialogVisible = false
      //   this.notify('发送成功')
      // })
      console.log('hahha')
    },
    handleCloseSendMail(arg) {
      this.sendMailVisible = false
      this.delData(arg)
    },
    handleChangeTemplate(id) {
      console.log(id, 1111)
      this.replaytemplateoptions.forEach(item => {
        if (id === this.chooseReplayTemplate) {
          this.replaytemplatebody = item.body
        }
      })
    },
    delData(id) {
      this.data.forEach((v, i) => {
        if (id === v.id) {
          this.data.splice(i, 1)
        }
      })
    },
    GetPaypalCaseInfo(transaction_id) {
      console.log('test')
    },
    handleReplayEmail(row) {
      this.replyemail.receiver_email = row.mail_from
      this.replyemail.emailbox_id = row.id
      this.replyemail.subject = 'Re:' + row.subject
      this.replyemail.body = "&nbsp;&nbsp;<br>---Original--=<br><div style='display:block'>" + row.body + '</div>'
      // test
      this.pre_subject = this.replyemail.subject
      this.pre_body = this.replyemail.body
      this.mail_to = row.mail_from
      this.mail_receiver = row.mail_to
      this.emailbox_id = row.id
      this.sendMailVisible = true
      // this.replayDialogVisible = true
      // this.$nextTick(() => {
      //   if (this.$refs.mt.hasInit) {
      //     this.$refs.mt.setContent(this.replyemail.body)
      //   }
      // })
      // this.GetOrderInfomation(row.mail_from)
      // this.replyemail.send_account = ''
      // this.email_accounts.forEach(item => {
      //   if (row.mail_to === item.account) {
      //     this.replyemail.send_account = item.id
      //   }
      // })
    },
    handleProcessLater(id) {
      if (id === '') {
        return
      }
      Put(id, {
        later: 'true'
      }).then((response) => {
        this.delData(id)
      })
    },
    handleDrawer(row) {
      this.currentrow = row
      this.drawer = true
      this.fetchEmailBody()
    },
    resetTemp() {
      this.temp = {
        later: true,
        processor_id: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        is_sended: this.is_sended,
        later: this.later,
        is_reply: true,
        processor_id: this.processor_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleModify(row) {
      Put(row.id, {
        processed: row.processed
      }).then((response) => {
        this.notify('更新成功')
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.domain}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改邮件:${row.subject} from ${row.mail_from}`
          this.temp.id = row.id
          this.temp.processor_id = row.processor_id
          this.temp.later = true
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (_data.project_id === '') {
            alert('必须选择项目')
            return
          }
          if (!_data.account.length) {
            alert('必须填写邮箱账号')
            return
          }
          if (!_data.password.length) {
            alert('必须填写密码')
            return
          }
          if (!_data.smtp_host.length) {
            alert('必须填写smtp_host')
            return
          }
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, {
            processor_id: _data.processor_id,
            later: _data.later
          }).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeWebDialog', false)
    }
  }
}
</script>
<style>
.unread {
    font-weight: 700;
  }
</style>
<style scoped>
  .mt-dialog >>> .el-dialog {
    margin-top: 5px !important;
    top: 10px;
    /*margin: 168px auto !important;*/
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
  .el-container >>> .pointer {
    cursor: pointer;
    color: #409EFF;
  }

  .el-container >>> a:visited {
    color: purple;
  }

  .el-container >>> a:link {
    color: #409EFF;
  }

  .el-container >>> a:active {
    color: red;
  }
  .app-container >>> a:hover {
    color: red;
    text-decoration: underline;
  }
</style>
